<template>
	<view class="cart_info">
		<!-- 菜单导航栏 -->
		<view class="cart_top">
			<view class="title">
				<view @tap="menu_selected_event" data-type="xh" :style="{color: move_state === 0 ? 'red' : 'black'}">现货
				</view>
				<view @tap="menu_selected_event" data-type="dh" :style="{color: move_state === 1 ? 'red' : 'black'}">定货
				</view>
				<view @click="edit">{{edit_status?'编辑':'管理'}}</view>
			</view>
		</view>
		<!-- 内容详情 -->
		<view class="">
			<view class="cart_list">
				<view class="cart_list_img" v-show="dataList.length<=0">
					<image src="https://t1.chowtaiking.com.cn/img/ruoyi/2025/03/10/082c37eb734d4394b0db2e351d974252.png"
						mode="widthFix"></image>
				</view>
				<view class="goods_info" :class="{'goods_info_item':item.inventory == 0}" v-for="(item,index) in dataList" :key="item.goods_id">
					<view class="select" :data-index="index" @tap="selected_event">
						<!-- <image :src="(item.selected || false)?select_url[1]:select_url[0]"></image> -->
						<image v-if="item.inventory > 0"
							:src="(item.selected || false) ? select_url[1] : select_url[0]"></image>
						<text v-else>已失效</text>
					</view>
					<view class="info">
						<view class="placard" @click="OnDetail(item.goods_id)">
							<image :src="item.images" mode=""></image>
						</view>
						<view class="details_info">
							<view class="info_title">
								<text>{{item.title}}</text>
							</view>
							<view class="detail">
								<text>金重：约{{item.gold_weight}}g</text>
							</view>
							<view class="detail">
								<text>款号：{{item.bar_code}}</text>
							</view>
							<view class="price">
								<view class="price_info">
									<text>单价：￥{{((item.price)*1).toFixed(2)}}</text>
									<text>价格：￥{{((item.price * item.stock) * 1).toFixed(2)}}</text>
								</view>
								<view class="add" v-if="(item.is_error || 0) != 1 && common_site_type != 1">
									<text :data-index="index" data-type="0" @tap="goods_buy_number_event">-</text>
									<input @blur="goods_buy_number_blur" type="number" :value="item.stock"
										:data-index="index" disabled="true">
									<text :data-index="index" data-type="1" @tap="goods_buy_number_event">+</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 底部 -->
				<view class="footer" v-show="!showFooter">
					<!-- 现货全选 -->
					<view class="footer_all" @tap="selected_s_event" v-if="move_state == 0">
						<image :src="is_selected_s_all ? select_url[1] : select_url[0]"></image>
						<view>全选</view>
					</view>

					<!-- 订货全选 -->
					<view class="footer_all" @tap="selected_o_event" v-else>
						<image :src="is_selected_o_all ? select_url[1] : select_url[0]"></image>
						<view>全选</view>
					</view>
					<view class="total" v-show="state === 2?!state:!edit_status">合计：
						<text style="color: red;">￥{{ total_price}}</text>
					</view>
					<view class="settlement">
						<button @click="cart_all_remove_event" v-if="edit_status">删除</button>
						<button @tap="buy_submit_event" v-else>结算</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp()
	export default {
		data() {
			return {
				edit_status: false,
				move_state: 0,
				select_url: ['https://t1.chowtaiking.com.cn/img/ruoyi/2025/03/10/af1873cb84b34f21a16bfc0e4cb20522.png',
					'https://t1.chowtaiking.com.cn/img/ruoyi/2025/03/10/6e13315dca0b4ca5aa9d9c26caa25531.png'
				],
				spotGoods: [],
				orderGoods: [],
				dataList: [],
				total_price: '0.00',
				cart_num: "",
				entryTime: 0,
				is_selected_s_all: false, // 现货是否全选
				is_selected_o_all: false, // 订货是否全选
			}
		},
		// 退出页面仍然保持状态
		onUnload() {
			 uni.setStorageSync('cart_selected_state', {
			    spotSelected: this.is_selected_s_all,
			    orderSelected: this.is_selected_o_all,
			    goodsData: [...this.spotGoods, ...this.orderGoods]
			  });
			this.OnEntryTime();
		},
		computed: {
		  is_selected_s_alls() {
		    return this.spotGoods.length > 0 && this.spotGoods.every(item => item.selected);
		  },
		  is_selected_o_alls() {
		    return this.orderGoods.length > 0 && this.orderGoods.every(item => item.selected);
		  }
		},
		methods: {
			OnEntryTime() {
				var radarlog_data = {
					pageUrl: "pages/cart/cart",
					name: "购物车页面",
					remark: "购物车页面停留时间",
					entryTime: this.entryTime,
				}
				uni.request({
					url: app.globalData.get_request_url("radarlog/add"),
					data: radarlog_data,
					method: "POST",
					success: (res) => {
						console.log(res, "购物车页面停留时间");
					}
				})
			},
			// 初始化
			init() {
				var user = app.globalData.get_user_info(this, "init", "");
				if (user != false) {
					// 用户未绑定用户则转到登录页面
					if (app.globalData.user_is_need_login(user)) {
						uni.navigateTo({
							url: "/pages/login/login?event_callback=init"
						})

					} else {
						this.getCart_goods();
						// 记录用户进来时间
						this.entryTime = Date.now();
					}
				}
			},
			// 获取数据
			getCart_goods() {
				this.move_state = 0;
				var url = app.globalData.get_request_url("cart/index");
				uni.request({
					url: url,
					method: 'POST',
					data: {},
					dataType: 'json',
					success: (res) => {
						uni.stopPullDownRefresh();
						if (res.data.code == 200) {
							var data = res.data.data;
							var sdata_list = [];
							var odata_list = [];
							if ((data.data || null) != null) {
								this.cart_num = data.buy_number
								// if (this.cart_num != null) {
								// 	uni.setTabBarBadge({
								// 		index: 3,
								// 		text: String(this.cart_num)
								// 	})
								// }
								for (let item of data.data) {
									if (item.buy_event_type === "现货")
										sdata_list.push(item)
									else
										odata_list.push(item)
								}

							} else {
								this.is_selected_s_all = false;   //现货是否全选
								this.is_selected_o_all = false;   //订货是否全选
								// uni.removeTabBarBadge({
								// 	index: 2
								// });
							}
							this.spotGoods = sdata_list;
							this.orderGoods = odata_list;
							console.log(this.orderGoods,'this.orderGoods');
							if (this.move_state == 0) {
								this.dataList = this.spotGoods;
							}
							console.log(this.dataList,'this.dataList');
							// 查看是否全选
							if(this.is_selected_s_all) {
							   this.spotGoods.forEach(item => item.selected = true);
							 }
							 if(this.is_selected_o_all) {
							   this.orderGoods.forEach(item => item.selected = true);
							 }
							 
						} else {
							if (app.globalData.is_login_check(res.data, this, 'get_data')) {
								uni.showToast({
									icon: 'none',
									title: res.data.msg,
									duration: 3000
								});
							}
						}
					}
				})
			},
			edit() {
				this.edit_status = !this.edit_status
			},
			// 数量操作事件
			goods_buy_number_event(e) {
				var index = e.currentTarget.dataset.index || 0;
				var type = parseInt(e.currentTarget.dataset.type) || 0;
				var temp_number = parseInt(this.dataList[index]['stock']);
				var buy_event_type = this.dataList[index]['buy_event_type'];
				var buy_max_number = parseInt(this.dataList[index]['buy_max_number']);
				// inventory    buy_event_type  buy_max_number

				var buy_number = (type == 0) ? temp_number - 1 : temp_number + 1;
				if (buy_number < 1) {
					buy_number = 1;
					uni.showToast({
						title: '数量至少为1哦！',
						icon: 'none'
					})
					return;
				}

				if (buy_event_type == '现货') {
					if (buy_number > buy_max_number) {
						buy_number = buy_max_number;
						uni.showToast({
							title: '库存不足',
							icon: 'none'
						});
						return;
					}
				}
				this.goods_buy_number_func(index, buy_number);
			},
			// 数量算法
			goods_buy_number_func(index, buy_number) {
				var temp_data_list = this.dataList;
				let goods = temp_data_list[index]
				uni.showLoading({
					title: '处理中...',
					mask: true
				});
				const data = {
					"id": goods.id,
					"goods_id": goods.goods_id,
					"stock": buy_number
				}
				let url = app.globalData.get_request_url("cart/stock");
				uni.request({
					url: url,
					method: "POST",
					data: data,
					success: (res) => {
						uni.hideLoading();
						if (res.data.code == 200) {
							var data = res.data.data;
							goods.stock = data.stock;
							this.cart_selected_calculate();
						} else {
							if (app.globalData.is_login_check(res.data, this, 'get_data')) {
								uni.showToast({
									icon: 'none',
									title: res.data.msg,
									duration: 3000
								});
							}
						}
					}
				})
			},
			// 选中处理
			menu_selected_event(e) {
				var type = e.currentTarget.dataset.type || null;
				if (type == 'xh') {
					this.move_state = 0;
					this.dataList = this.spotGoods;
					var temp_data_list = this.dataList;
					var temp_is_selected_all = this.is_selected_s_all;
					for (var i in temp_data_list) {
						temp_data_list[i]['selected'] = temp_is_selected_all;
					}
					this.is_selected_s_all = temp_is_selected_all;
					this.dataList = temp_data_list;
					this.cart_selected_calculate();
				} else {
					this.move_state = 1;
					this.dataList = this.orderGoods;
					var temp_data_list = this.dataList;
					var temp_is_selected_all = this.is_selected_o_all;
					for (var i in temp_data_list) {
						temp_data_list[i]['selected'] = temp_is_selected_all;
					}
					this.is_selected_o_all = temp_is_selected_all;
					this.dataList = temp_data_list;
					this.cart_selected_calculate();
				}
			},
			// 选中处理
			selected_event(e) {
				var index = e.currentTarget.dataset.index || 0;
				var temp_data_list = this.dataList;
				this.$set(this.dataList, index, {
					...this.dataList[index],
					selected: !this.dataList[index].selected
				});
				this.dataList = temp_data_list;
				var temp_is_selected_all = this.dataList.every(item => item['selected']);
				var buy_event_type = "";
				this.dataList.forEach(item => {
					buy_event_type = item.buy_event_type
				})
				if (buy_event_type == '现货') {
					this.is_selected_s_all = temp_is_selected_all; // 现货是否全选
				} else {
					this.is_selected_o_all = temp_is_selected_all; // 订货是否全选
				}
				this.cart_selected_calculate();
			},

			// 选中计算
			cart_selected_calculate() {
				var total_price = 0;
				var cart_total = 0;
				var temp_data_list = this.dataList;

				for (var i in temp_data_list) {
					if ((temp_data_list[i]['selected'] || false) == true) {
						if (temp_data_list[i]['storeCategoryName'] == '酒水') {
							total_price += parseInt(temp_data_list[i]['stock']) * parseFloat(temp_data_list[i][
								'original_price'
							]);
						} else {
							total_price += parseInt(temp_data_list[i]['stock']) * parseFloat(temp_data_list[i]['price']);
						}
					} else {
						cart_total += parseInt(temp_data_list[i]['stock']);
					}
				}
				this.total_price = total_price.toFixed(2);
				// if (cart_total <= 0) {
				// 	uni.hideTabBarRedDot({
				// 		index: 3
				// 	});
				// } else {
				// 	uni.setTabBarBadge({
				// 		index: 3,
				// 		text: String(cart_total)
				// 	})
				// }
			},
			// 现货全选
			selected_s_event() {
				let temp_data_list = this.spotGoods;
				let temp_is_selected_all = this.is_selected_s_all;
				temp_is_selected_all = temp_is_selected_all == true ? false : true;
				for (let i in temp_data_list) {
					temp_data_list[i]['selected'] = temp_is_selected_all;
				}
				this.is_selected_s_all = temp_is_selected_all;
				this.spotGoods = temp_data_list;
				this.cart_selected_calculate();
			},

			// 订货全选
			selected_o_event() {
				let temp_data_list = this.orderGoods;
				let temp_is_selected_all = this.is_selected_o_all;
				temp_is_selected_all = temp_is_selected_all == true ? false : true;

				for (let i in temp_data_list) {
					temp_data_list[i]['selected'] = temp_is_selected_all;
				}

				this.is_selected_o_all = temp_is_selected_all;
				this.orderGoods = temp_data_list;
				this.cart_selected_calculate();
			},

			// 数量输入事件
			goods_buy_number_blur(e) {
				var index = e.currentTarget.dataset.index || 0;
				var buy_number = parseInt(e.detail.value) || 1;
				this.goods_buy_number_func(index, buy_number);
			},
			// 批量删除操作
			cart_all_remove_event(e) {
				uni.showModal({
					title: '温馨提示',
					content: '挑了这么久，真的要删除吗？',
					confirmText: '确认',
					cancelText: '暂不',
					success: result => {
						if (result.confirm) {
							var data = [];
							var temp_data_list = this.dataList || [];
							for (var i in temp_data_list) {
								if ((temp_data_list[i]['selected'] || false) == true) {
									data.push(temp_data_list[i]['id']);
								}
							}
							if (data.length <= 0) {
								uni.showToast({
									title: '请先选择商品'
								})
								return false;
							}
							this.cart_delete(data.join(','));
						}
					}
				});
			},
			/**
			 * 删除
			 */
			cart_delete(ids) {
				let url = app.globalData.get_request_url("/cart/delete");
				uni.request({
					url: url,
					data: {
						id: ids
					},
					method: 'POST',
					success: (res) => {
						if (res.data.code == 200) {
							var data = res.data.data;
							this.cart_num = data.buy_number;
							var temp_list = [];
							var temp_id_arr = ids.split(',');
							var temp_data_list = this.dataList;
							for (var i in temp_data_list) {
								if (temp_id_arr.indexOf(temp_data_list[i]['id']) == -1) {
									temp_list.push(temp_data_list[i]);
								}
							}
							this.is_selected_s_all = false;   //现货是否全选
							this.is_selected_o_all = false;   //订货是否全选
							this.dataList = temp_list;

							if (this.move_state == 0) {
								this.spotGoods = temp_list;
							} else {
								this.orderGoods = temp_list;
							}
							uni.showToast({
								title: "删除成功"
							})
							this.cart_selected_calculate();
							// if (this.cart_num != null) {
							// 	uni.setTabBarBadge({
							// 		index: 3,
							// 		text: String(this.cart_num)
							// 	})
							// } else {
							// 	uni.hideTabBarRedDot({
							// 		index: 3
							// 	});
							// }
						} else {
							if (app.globalData.is_login_check(res.data, this, 'get_data')) {
								uni.showToast({
									icon: 'none',
									title: res.data.msg,
									duration: 3000
								});
							}
						}
						uni.hideLoading()
					}
				})
			},
			// 选中结算
			buy_submit_event() {
				var selected_count = 0;
				var ids = [];
				var temp_data_list = this.dataList || [];
				for (var i in temp_data_list) {
					if ((temp_data_list[i]['selected'] || false) == true) {
						ids.push(temp_data_list[i]['id']);
						selected_count++;
					}
				}
				if (selected_count <= 0) {
					uni.showToast({
						title: '请先选择商品'
					})
					return false;
				}
				var data = {
					buy_type: "cart",
					ids: ids.join(','),
				};
				if (this.move_state === 0 || this.move_state === 1) {
					uni.navigateTo({
						url: '/pages/confirmOrder/confirmOrder?data=' + JSON.stringify(data)
					});
				}
			},
			OnDetail(id) {
				uni.navigateTo({
					url: "/pages/goods_detail/goods_detail?id=" + id
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	/deep/ .popup .vue-ref {
		background-color: white !important;
	}

	#canvasId {
		background-color: white !important;
	}

	.canvas_main {
		width: 100%;
		height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: white !important;
	}

	.mixin(@jc, @ai) {
		display: flex;
		justify-content: @jc;
		align-items: @ai;
	}

	.size(@w, @h) {
		width: @w;
		height: @h;
	}

	.cart_list {
		padding-bottom: 100rpx;
		background-color: white;

		.cart_list_img {
			image {
				width: 100%;
				display: block;
				margin: auto;
			}
		}
		.goods_info_item {
			background-color: #f2f3f5;
		}
		.goods_info {
			width: 100%;
			padding: 20rpx 0;
			border-bottom: 1px solid #F8F8F8;
			.mixin(space-around, center);

			.select {
				width: 10%;
				text {
					color: gray;
					font-size: 12px;
				}

				image {
					.size(60rpx, 60rpx);
				}
			}

			.info {
				width: 80%;
				.mixin(start, center);

				.placard {

					margin-right: 20rpx;

					image {
						width: 160rpx;
						height: 160rpx;
					}
				}

				.details_info {
					width: 100%;
					.mixin(center, start);
					flex-direction: column;

					.info_title {
						width: 200px;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						color: white;

						text:first-child {
							font-size: 25rpx;
							font-weight: bold;
							background-color: red;
							color: white;
							border-radius: 10rpx;
							padding: 10rpx 5rpx;
							margin-right: 10rpx;
						}
					}

					.detail {
						width: 200px;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;

						text {
							font-size: 25rpx;
							color: #b5b5b5;
							margin-left: 10rpx;
						}

					}

					.price {
						width: 100%;
						.mixin(space-between, center);

						.price_info {
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;

							text:nth-child(1) {
								font-size: 25rpx;
								color: #b5b5b5;
							}

							text:nth-child(2) {
								color: red;
								font-size: 13px;
							}
						}

						.add {
							display: flex;
							justify-content: space-around;
							align-items: center;

							input {
								display: inline-block;
								border: #b5b5b5 1px solid;
								width: 50rpx;
								height: 50rpx;
								text-align: center;
								line-height: 50rpx;
								font-size: 12px;
							}

							text {
								display: inline-block;
								border: #b5b5b5 1px solid;
								width: 50rpx;
								height: 50rpx;
								text-align: center;
								line-height: 50rpx;
								font-size: 13px;
								font-weight: bold;
							}

						}

					}

				}

			}
		}
	}

	// 底部
	.footer {
		z-index: 999;
		// .mixin(space-around, center);
		.mixin(space-between, center);
		position: fixed;
		bottom: 0;
		background-color: white;
		.size(100%, 100rpx);

		.footer_all {
			.mixin(space-between, center);

			image {
				.size(60rpx, 60rpx);
				margin: 0 20rpx;
			}
		}

		.settlement {
			button {
				margin-right: 20rpx;
				background-color: red;
				border-radius: 20rpx;
				color: white;
				.size(175rpx, 70rpx);
				text-align: center;
				line-height: 70rpx;
			}

		}
	}

	.mixin(@jc, @ai) {
		display: flex;
		justify-content: @jc;
		align-items: @ai;
	}

	.size(@w, @h) {
		width: @w;
		height: @h;
	}

	.cart_info {
		.cart_top {
			z-index: 999;
			position: sticky;
			background-color: #F8F8F8;
			padding: 20rpx 0;
			top: 0;

			.title {
				display: flex;
				.mixin(space-around, center);

				view {
					width: 120rpx;
					text-align: center;
				}
			}
		}
	}
</style>